<?php
namespace app\index\controller;

use think\Request;
use app\common\model\Category as CategoryModel;
use app\common\service\Article as ArticleLogic;
use app\common\service\Book as BookLogic;
use app\index\controller\Base;

class Category extends Base
{
    protected $data = [];

    public function _initialize()
    {
        $this->data = $this->getData();
    }

    protected function getData()
    {
        return CategoryModel::getInfoByAlias(Request::instance()->param('alias'));
    }

    public function read()
    {
        if (!$this->data) {
            $this->error('您访问的栏目不存在');
        }

        // 数组键名转换为变量 并传值到模板
        foreach ($this->data as $k => $v) {
            $this->assign($k,$v);
        }

        switch ($this->data['module_id']) {
            case 1:
                $default_tpl = 'article_list_tpl';

                // 查询栏目下文章列表
                $articleLogic = new ArticleLogic();
                $map = array(
                    'category_id' => $this->data['id'],
                    'a.status'    => 1,
                );

                // 每页列表显示数量
                $limit = empty($this->data['limit']) ? $this->config('article_limit') : $this->data['limit'];
                $data = $articleLogic->getAll($map, 'id desc', $limit);

                // 传值到模板页
                $this->assign('list',$data['list']);
                $this->assign('page',$data['page']);
                break;
            case 2:
                $default_tpl = 'book_list_tpl';

                // 查询栏目下图书列表
                $bookLogic = new BookLogic();
                $map = array(
                    'category_id' => $this->data['id'],
                    'b.status'    => 1,
                );

                // 每页列表显示数量
                $limit = empty($this->data['limit']) ? $this->config('book_limit') : $this->data['limit'];
                $data = $bookLogic->getAll($map, 'id desc', $limit);

                // 传值到模板页
                $this->assign('list',$data['list']);
                $this->assign('page',$data['page']);
                break;
            case 3:
                $default_tpl = 'single_tpl';

                break;
        }

        // 模版 优先使用栏目独立模版配置
        return $this->fetch($this->template($default_tpl, $this->data['list_template']));
    }
}
